package com.gsm.phimhanhdong;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.androidquery.AQuery;
import com.google.analytics.tracking.android.EasyTracker;
import com.gsm.phimhanhdong.ContentNetworkInterface.GetAccesstokenSuccessEvent;
import com.gsm.phimhanhdong.ContentNetworkInterface.GetRequesttokenSuccessEvent;
import com.gsm.phimhanhdong.ContentNetworkInterface.GetTopFailEvent;
import com.gsm.phimhanhdong.ContentNetworkInterface.TopContentSuccessEvent;
import com.gsm.phimhanhdong.ContentNetworkInterface.TopEndOfContentEvent;
import com.gsm.phimhanhdong.ContentNetworkInterface.TopNoContentEvent;

import de.greenrobot.event.EventBus;

public class HomeListFragment extends BaseFragment implements
		OnItemClickListener,
		com.gsm.phimhanhdong.LoadMoreListView.OnLoadMoreListener {
	private String topType;
	private String currentStore;
	private final String KEY_CONTENT = "Fragment:List";
	private int START_NEW = 0;
	private int START_DOWNLOAD = 0;
	private int START_PAID = 0;
	private int START_HOT = 0;
	private boolean inited = false;
	private BackgroundTasks bgTask;
	private AQuery aq;
	private EventBus eventBus;
	private String accessToken;
	private LoadMoreListView listView;
	private ContentItemAdapter adapter;
	private List<ContentItemInfo> listContent;
	private PackageEventReceiver receiver;
	private String store;
	private ContentItemInfo contentItem;
	private ProgressDialog pDialog;
	private boolean isWatchMovie = false;
	private String versionName = "";
	private int greenTym = -1;
	private int purpleTym = -1;
	private DialogInterface.OnClickListener onClick;
	private MediumAdImageView banner1, banner2;
	private int versionId = 0;
	private String countryCode;

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString(KEY_CONTENT, topType);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		if (savedInstanceState != null) {
			topType = savedInstanceState.getString(KEY_CONTENT);
		}
		adapter = new ContentItemAdapter(getActivity(),
				R.layout.short_content_item, listContent);
		adapter.setStore(currentStore);
		aq.id(listView).adapter(adapter).itemClicked(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		eventBus.register(this);
	}

	@Override
	public void onPause() {
		super.onPause();
		eventBus.unregister(this);
	}

	public void init() {
		if (bgTask == null) {
			bgTask = new BackgroundTasks(getActivity());
		}
		if (inited) {
			return;
		}
		inited = true;
		bgTask.getRequestToken();

	}

	public void onEventMainThread(GetRequesttokenSuccessEvent e) {
		String request_token = e.request_token;
		Log.e("", "bg task" + bgTask);
		bgTask.getAccessToken(request_token);
	}

	public void onEventMainThread(GetAccesstokenSuccessEvent e) {

		this.accessToken = e.access_token;
		if (accessToken != null) {
			Log.e("", "acess_token home frage" + accessToken);
			loadData(0);
//			loadTextAd();
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (bgTask == null) {
			bgTask = new BackgroundTasks(getActivity());
		}
		mParent = inflater.inflate(R.layout.layout_listing, null);
		aq = new AQuery(mParent);
		listView = (LoadMoreListView) mParent.findViewById(R.id.list_content);
		listView.setOnLoadMoreListener(this);
		aq.id(R.id.btn_retry).gone();
		aq.id(R.id.progress).visible();
		return mParent;
	}

	private void loadData(int start) {
		if (topType.equalsIgnoreCase(getResources().getString(R.string.top_new)
				.toUpperCase(Locale.US))) {
			getTopNew(accessToken, currentStore, start);
		} else if (topType.equalsIgnoreCase(getResources().getString(
				R.string.top_download).toUpperCase(Locale.US))) {
			getTopDownload(accessToken, currentStore, start);
		} else if (topType.equalsIgnoreCase(getResources().getString(
				R.string.top_paid).toUpperCase(Locale.US))) {
			getTopPaid(accessToken, currentStore, start);
		} else if (topType.equalsIgnoreCase(getResources().getString(
				R.string.hot_app).toUpperCase(Locale.US))) {
			getHot(accessToken, currentStore, start);
		}
	}

	private void loadTextAd() {
		String bannerStore;
		if (currentStore.equalsIgnoreCase("books")) {
			bannerStore = "ebook_android";
		} else if (currentStore.equalsIgnoreCase("comics")) {
			bannerStore = "comic_android";
		} else if (currentStore.equalsIgnoreCase("movies")) {
			bannerStore = "film_android";
		} else {
			bannerStore = "android";
		}
		bgTask.getTextBanners(accessToken, bannerStore, topType);
	}

	private void getHot(String accessToken, String store, int start) {
		int storeId = 2;
		int cateId = 0;
		if (store.equalsIgnoreCase("apps")) {
			storeId = 2;
			cateId = -1;
		} else if (store.equalsIgnoreCase("games")) {
			storeId = 2;
			cateId = -2;
		} else if (store.equalsIgnoreCase("movies")) {
			storeId = 6;
		} else if (store.equalsIgnoreCase("books")) {
			storeId = 4;
		} else if (store.equalsIgnoreCase("comics")) {
			storeId = 5;
		} else {
			storeId = 2;
			cateId = 0;
		}
		bgTask.getTopContent(getResources().getString(R.string.hot_app),
				cateId, accessToken, storeId, start);
	}

	private void getTopPaid(String accessToken, String store, int start) {
		int storeId = 2;
		int cateId = 0;
		if (store.equalsIgnoreCase("apps")) {
			storeId = 2;
			cateId = -1;
		} else if (store.equalsIgnoreCase("games")) {
			storeId = 2;
			cateId = -2;
		} else if (store.equalsIgnoreCase("movies")) {
			storeId = 6;
		} else if (store.equalsIgnoreCase("books")) {
			storeId = 4;
		} else if (store.equalsIgnoreCase("comics")) {
			storeId = 5;
		} else {
			storeId = 2;
			cateId = 0;
		}
		bgTask.getTopContent(getResources().getString(R.string.top_paid),
				cateId, accessToken, storeId, start);
	}

	private void getTopDownload(String accessToken, String store, int start) {
		int storeId = 2;
		int cateId = 0;
		if (store.equalsIgnoreCase("apps")) {
			storeId = 2;
			cateId = -1;
		} else if (store.equalsIgnoreCase("games")) {
			storeId = 2;
			cateId = -2;
		} else if (store.equalsIgnoreCase("movies")) {
			storeId = 6;
		} else if (store.equalsIgnoreCase("books")) {
			storeId = 4;
		} else if (store.equalsIgnoreCase("comics")) {
			storeId = 5;
		} else {
			storeId = 2;
			cateId = 0;
		}
		bgTask.getTopContent(getResources().getString(R.string.top_download),
				cateId, accessToken, storeId, start);
	}

	private void getTopNew(String accessToken, String store, int start) {
		int storeId = 2;
		int cateId = 0;
		if (store.equalsIgnoreCase("apps")) {
			storeId = 2;
			cateId = -1;
		} else if (store.equalsIgnoreCase("games")) {
			storeId = 2;
			cateId = -2;
		} else if (store.equalsIgnoreCase("movies")) {
			storeId = 6;
		} else if (store.equalsIgnoreCase("books")) {
			storeId = 4;
		} else if (store.equalsIgnoreCase("comics")) {
			storeId = 5;
		} else {
			storeId = 2;
			cateId = 0;
		}
		bgTask.getTopContent(getResources().getString(R.string.top_new),
				cateId, accessToken, storeId, start);
	}

	// @Override
	// public void onStop() {
	// // TODO Auto-generated method stub
	// super.onStop();
	// EasyTracker.getInstance().activityStop(getActivity());
	// }

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		listView.setAdapter(null);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mContext.unregisterReceiver(receiver);
	}

	// @Override
	// public void onStart() {
	// // TODO Auto-generated method stub
	// super.onStart();
	// EasyTracker.getInstance().activityStart(getActivity());
	// }

	public void onEventMainThread(TopContentSuccessEvent event) {
		if (event.getTopType().equalsIgnoreCase(topType)) {
			aq.id(listView).visible();
			aq.id(R.id.btn_retry).gone();
			aq.id(R.id.progress).gone();
			aq.id(R.id.text_no_content).gone();
			for (ContentItemInfo item : event.getItemList()) {
				listContent.add(item);
			}
			adapter.notifyDataSetChanged();
			listView.onLoadMoreComplete();
		}
	}

	public void onEventMainThread(GetTopFailEvent event) {
		if (event.getType().equalsIgnoreCase(topType)) {
			aq.id(listView).gone();
			aq.id(R.id.btn_retry).visible().clicked(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					aq.id(listView).gone();
					listView.setOnLoadMoreListener(HomeListFragment.this);
					aq.id(R.id.btn_retry).gone();
					aq.id(R.id.progress).visible();
					aq.id(R.id.text_no_content).gone();
					loadData(0);
					loadTextAd();
				}
			});
			aq.id(R.id.progress).gone();
			listView.setOnLoadMoreListener(null);
		}
	}

	public void onEventMainThread(TopNoContentEvent e) {
		if (e.getType().equalsIgnoreCase(topType)) {
			aq.id(listView).gone();
			aq.id(R.id.btn_retry).gone();
			aq.id(R.id.progress).gone();
			aq.id(R.id.text_no_content).visible();
		}
	}

	public void onEventMainThread(TopEndOfContentEvent e) {
		if (e.getType().equalsIgnoreCase(topType)) {
			listView.onLoadMoreComplete();
			listView.setOnLoadMoreListener(null);
		}
	}


	private boolean appInstalledOrNot(String uri) {
		PackageManager pm = getActivity().getPackageManager();
		boolean app_installed = false;
		try {
			pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
			app_installed = true;
		} catch (PackageManager.NameNotFoundException e) {
			app_installed = false;
		}
		Log.e("", "appInstalledOrNot " + app_installed);
		return app_installed;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long arg3) {
		if (!appInstalledOrNot("com.appstoregp.vn")) {
			AlertDialog.Builder builder = new Builder(getActivity());
			builder.setTitle(getResources().getString(R.string.title_dialog))
					.setMessage(getResources().getString(R.string.msg_dialog))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface arg0,
										int arg1) {
									// TODO Auto-generated method stub
									Intent intent = new Intent();
									intent.setAction(Intent.ACTION_VIEW);
									intent.addCategory(Intent.CATEGORY_BROWSABLE);
									intent.setData(Uri
											.parse("market://details?id=com.appstoregp.vn"));
									startActivity(intent);
									arg0.dismiss();
								}
							})
					;
			AlertDialog dialog = builder.create();
			dialog.setCancelable(false);
			dialog.show();

		} else {
			ContentItemInfo item = (ContentItemInfo) parent
					.getItemAtPosition(position);
			Intent intent = new Intent();
			intent.setAction(Intent.ACTION_VIEW);
			intent.addCategory(Intent.CATEGORY_BROWSABLE);
			intent.setData(Uri.parse("http://appstore.vn/android/details?id="
					+ item.getPackageName()));
			intent.putExtra(Constants.PREVIOUS_SCREEN, currentStore + "/"
					+ topType);
			intent.putExtra(Constants.SLUG, item.getApplicationId());
			intent.putExtra(Constants.PACKAGE_NAME, item.getPackageName());
			intent.putExtra(Constants.KEY_REFERER, "direct");
			intent.putExtra(Constants.STORE_KEY,
					getArguments().getString(Constants.STORE_KEY));
			startActivity(intent);
		}
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		if (topType.equalsIgnoreCase(getResources().getString(R.string.top_new)
				.toUpperCase(Locale.US))) {
			START_NEW = START_NEW + 20;
			loadData(START_NEW);
		} else if (topType.equalsIgnoreCase(getResources().getString(
				R.string.top_download).toUpperCase(Locale.US))) {
			START_DOWNLOAD = START_DOWNLOAD + 20;
			loadData(START_DOWNLOAD);
		} else if (topType.equalsIgnoreCase(getResources().getString(
				R.string.top_paid).toUpperCase(Locale.US))) {
			START_PAID = START_PAID + 20;
			loadData(START_PAID);
		} else if (topType.equalsIgnoreCase(getResources().getString(
				R.string.hot_app).toUpperCase(Locale.US))) {
			START_HOT = START_HOT + 20;
			loadData(START_HOT);
		}
	}

	@Override
	protected void initVariables() {
		// TODO Auto-generated method stub
		EasyTracker.getInstance().setContext(mContext);
		topType = getArguments().getString(Constants.TOP);
		currentStore = getArguments().getString(Constants.STORE_KEY);
		eventBus = EventBus.getDefault();
		listContent = new ArrayList<ContentItemInfo>();
		receiver = new PackageEventReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_PACKAGE_ADDED);
		filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
		filter.addDataScheme("package");
		mContext.registerReceiver(receiver, filter);
		countryCode = getStaticCountryCode(mContext);
	}

	@Override
	protected void initActions() {
		// TODO Auto-generated method stub

	}

	private class PackageEventReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equalsIgnoreCase(Intent.ACTION_PACKAGE_ADDED)) {
				String installedName = intent.getDataString().split(":")[1];
				String packageName = "";
				for (ContentItemInfo item : listContent) {
					packageName = item.getPackageName();
					if (packageName == null || !packageName.contains(".")) {
						continue;
					}
					if (packageName.equalsIgnoreCase(installedName)) {
						item.setInstalled(true);
					}
				}
				adapter.notifyDataSetChanged();
			} else if (action.equalsIgnoreCase(Intent.ACTION_PACKAGE_REMOVED)) {
				String packageName = "";
				String uninstalledName = intent.getDataString().split(":")[1];
				for (ContentItemInfo item : listContent) {
					packageName = item.getPackageName();
					if (packageName == null || !packageName.contains(".")) {
						continue;
					}
					if (packageName.equalsIgnoreCase(uninstalledName)) {
						item.setInstalled(false);
					}
				}
				adapter.notifyDataSetChanged();
			}
		}
	}

	public static String getStaticCountryCode(Context context) {
		SharedPreferences pref = PreferenceManager
				.getDefaultSharedPreferences(context);
		String countryCode = pref.getString(Constants.COUNTRY_CODE, "us");
		return countryCode;
	}

}
